﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebServerLib;
using System.Data;
using System.Globalization;
using GraphicLib;
using System.IO;
using SettLib;
using DatabaseLib;

// Command handler Class v.1.0
// by George Makarov
// Email: georgemakarov1@yandex.ru

namespace CommandLib
{
    public class cCommand
    {
        private cWebServer WebServer;
        //public delegate void dExecuteQuery(string Query);
        //private dExecuteQuery ExecuteQuery;
        //public delegate void dExecuteQueryBatch(List<string> Query);
        //private dExecuteQueryBatch ExecuteQueryBatch;
        //public delegate DataTable dGetQueryTable(string Query);
        //private dGetQueryTable GetQueryTable;
        //public delegate object dGetQueryObject(string Query);
        //private dGetQueryObject GetQueryObject;
        //public delegate string dGetQueryValue(string Query);
        //private dGetQueryValue GetQueryValue;
        public delegate void dErrorHandler(Exception ex);
        public event dErrorHandler ErrorHandler;
        public delegate void dLogHandler(string Msg);
        public event dLogHandler LogHandler;
        private cSettings Settings;
        private DB db;

        public cCommand(cWebServer pWebServer, cSettings pSett, DB pDB)
        {
            WebServer = pWebServer;
            Settings = pSett;
            db = pDB;
        }

        public string ExecuteCommand(string command, int SessionNum)
        {
            if (LogHandler != null)
                LogHandler("CommandLib: Executing command \"" + command + "\"");
            string Result = string.Empty;
            cWebServer.cSession SessionData = WebServer.GetSessionData(SessionNum);
            try
            {
                switch (command.ToLower())
                {
                    #region ShowSessionID
                    case "showsessionid":
                        {
                            Result += ShowSessionID(SessionData);
                            break;
                        }
                    #endregion
                    #region getaddressautocompletedata
                    case "getaddressautocompletedata":
                        {
                            Result += GetAddressAutocompleteData(SessionData);
                            break;
                        }
                    #endregion
                    #region showuserinfo
                    case "showuserinfo":
                        {
                            Result += ShowUserInfo(SessionData);
                            break;
                        }
                    #endregion
                    #region ShowGeneralSettings
                    case "showgeneralsettings":
                        {
                            Result += ShowGeneralSettings(SessionData);
                            break;
                        }
                    #endregion
                    #region ShowSyslogSettings
                    case "showsyslogsettings":
                        {
                            Result += ShowSyslogSettings(SessionData);
                            break;
                        }
                    #endregion
                    #region ShowWebserverSettings
                    case "showwebserversettings":
                        {
                            Result += ShowWebserverSettings(SessionData);
                            break;
                        }
                    #endregion
                    #region showreportmaxdetailed
                    case "showreportmaxdetailed":
                        {
                            Result += ShowReportMaxDetailed(SessionData);
                            break;
                        }
                    #endregion
                    #region ShowGraphicByUsers
                    case "showgraphicbyusers":
                        {
                            Result += ShowGraphicByUsers(SessionData);
                            break;
                        }
                    #endregion
                    #region ShowReportByUsers
                    case "showreportbyusers":
                        {
                            Result += ShowReportByUsers(SessionData);
                            break;
                        }
                    #endregion
                    #region ShowPeriodByUsers
                    case "showperiodbyusers":
                        {
                            Result += ShowPeriodByUsers(SessionData);
                            break;
                        }
                    #endregion
                    #region ShowReportUserDetailed
                    case "showreportuserdetailed":
                        {
                            Result += ShowReportUserDetailed(SessionData);
                            break;
                        }
                    #endregion
                    #region insertuserstocombobox
                    case "insertuserstocombobox":
                        {
                            Result += InsertUsersToCombobox(SessionData);
                            break;
                        }
                    #endregion
                    #region insertaccessleveltocombobox
                    case "insertaccessleveltocombobox":
                        {
                            Result += InsertAccessLevelToCombobox(SessionData);
                            break;
                        }
                    #endregion
                    #region isuserloggedin
                    case "isuserloggedin":
                        {
                            Result += IsUserLoggedIn(SessionData);
                            break;
                        }
                    #endregion
                    #region insertsrcaddresstocombobox
                    case "insertsrcaddresstocombobox":
                        {
                            Result += InsertSrcAddressToCombobox(SessionData);
                            break;
                        }
                    #endregion
                    #region insertdstaddresstocombobox
                    case "insertdstaddresstocombobox":
                        {
                            Result += InsertDstAddressToCombobox(SessionData);
                            break;
                        }
                    #endregion
                    #region showuserlist
                    case "showuserlist":
                        {
                            Result += ShowUserList(SessionData);
                            break;
                        }
                    #endregion
                    #region showusersdata
                    case "showusersdata":
                        {
                            Result += ShowUsersData(SessionData);
                            break;
                        }
                    #endregion
                    #region insertdatenow
                    case "insertdatenow":
                        {
                            Result += InsertDateNow(SessionData);
                            break;
                        }
                    #endregion
                    #region insertdatetomorrow
                    case "insertdatetomorrow":
                        {
                            Result += InsertDateTomorrow(SessionData);
                            break;
                        }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                if (ErrorHandler != null)
                    ErrorHandler(new Exception("Ошибка при выполнении команды \"" + command + "\"", ex));
                throw ex;
            }
            return Result;
        }

        private int GetShowingColumnsCount(bool[] ShowingColumns)
        {
            int Result = 0;
            foreach (bool Show in ShowingColumns)
                if (Show)
                    Result++;
            return Result;
        }

        private string BytesToMultipleBytes(Int64 Bytes, bool Short, int Precision)
        {
            string[] Measure = new string[] { "байт", "Кбайт", "Мбайт", "Гбайт", "Тбайт", "Пбайт" };
            string[] MeasureShort = new string[] { "б", "Кб", "Мб", "Гб", "Тб", "Пб" };
            string Result = string.Empty;
            double dBytes = Bytes;
            int Multiple = 0;
            while (dBytes > 1024)
            {
                dBytes = dBytes / 1024;
                Multiple++;
            }
            Result = dBytes.ToString("F" + Precision.ToString()) + " ";
            if (Short)
                Result += MeasureShort[Multiple];
            else
                Result += Measure[Multiple];
            return Result;
        }

        private string DataTableToSelectControl(DataTable DT, string SelectedIndex, bool SIByValueOrOption, int ValueField, int OptionField)
        {
            string Result = string.Empty;
            if (DT != null)
            {
                if (DT.Rows.Count != 0)
                    for (int i = 0; i < DT.Rows.Count; i++)
                    {
                        int SIColumn = SIByValueOrOption ? ValueField : OptionField;

                        if (DT.Rows[i][SIColumn].ToString() == SelectedIndex)
                        {
                            Result = DataTableToSelectControl(DT, i, ValueField, OptionField);
                            break;
                        }

                    }
                if ((DT.Rows.Count != 0) && (Result == string.Empty))
                    Result = DataTableToSelectControl(DT, 0, ValueField, OptionField);
            }
            return Result;
        }

        private string DataTableToSelectControl(DataTable DT, int SelectedIndex, int ValueField, int OptionField)
        {
            string Result = string.Empty;
            if (DT != null)
            {
                int i = 0;
                if (DT.Rows.Count > 0)
                    foreach (DataRow DR in DT.Rows)
                    {

                        Result += "<option";
                        if (i == SelectedIndex) Result += " selected=\"selected\"";
                        Result += " value=\"" + DR[ValueField].ToString() + "\">";
                        Result += DR[OptionField].ToString();
                        Result += "</option>";
                        i++;
                    }
            }
            return Result;
        }

        //private string ObjectToString(object Data)
        //{
        //    string Result = string.Empty;
        //    if (!DBNull.Value.Equals(Data))
        //        Result = Data.ToString();
        //    return Result;
        //}

        private string ShowSessionID(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            Result = SessionData.SessionID.ToString();
            return Result;
        }

        private string GetAddressAutocompleteData(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            object oX_REQUESTED_WITH = cWebServer.GetHeaderValue(SessionData.Headers, "X-Requested-With");
            string sX_REQUESTED_WITH = string.Empty;
            if (oX_REQUESTED_WITH != null)
                sX_REQUESTED_WITH = oX_REQUESTED_WITH.ToString();
            if (sX_REQUESTED_WITH == "XMLHttpRequest")
            {
                object oWebQuery = cWebServer.GetParamValue(SessionData.Params, "q");
                if (oWebQuery != null)
                {
                    string sWebQuery = oWebQuery.ToString();
                    DataTable DT = db.GetQueryTable("Select top(20) * from TAddresses where IPAddress LIKE '" + sWebQuery + "%' Order by ipaddress");
                    if (DT.Rows.Count > 0)
                    {
                        int i = 0;
                        foreach (DataRow DR in DT.Rows)
                        {
                            Result += DR["IPAddress"].ToString() + "|" + i.ToString() + "|" + (DT.Rows.Count - 1).ToString() + "|" + DR["HostName"].ToString() + "\n";
                            i++;
                        }
                    }
                }
            }
            return Result;
        }

        private string ShowUserInfo(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            if (SessionData.UserID != Guid.Empty)
            {
                Result = "Вы вошли в систему как " + db.GetQueryValue("select fullname from TUsers where Userid='" + SessionData.UserID.ToString() + "'") + "<br>";
                Result += "Права доступа: " + db.GetQueryValue("Select name from taccesslevels where level=" + SessionData.AccessLevel.ToString());
                Result += "<div style=\"text-align:right\"><input type=\"button\" value=\"Выход\" onclick=\"javascript:logout()\"/></div>";
            }
            return Result;
        }

        private void UpdateSettings(List<cWebServer.stParam> Params, ref int SettParam, string URIParam, bool AllowNullValue)
        {
            int iValue = 0;
            object oValue = cWebServer.GetParamValue(Params, URIParam);
            if (oValue != null)
                iValue = Convert.ToInt32(oValue);
            if ((iValue != 0) || AllowNullValue)
                SettParam = iValue;
        }

        private void UpdateSettings(List<cWebServer.stParam> Params, ref string SettParam, string URIParam, bool AllowNullValue)
        {
            string sValue = string.Empty;
            object oValue = cWebServer.GetParamValue(Params, URIParam);
            if (oValue != null)
                sValue = oValue.ToString();
            if ((sValue != string.Empty) || AllowNullValue)
                SettParam = sValue;
        }

        private string ShowGeneralSettings(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            if ((SessionData.UserID == Guid.Empty) || (SessionData.AccessLevel > 2))
            {
                Result = "Отказано в доступе";
                return Result;
            }
            List<cWebServer.stParam> Params = SessionData.Params;
            object oAction = cWebServer.GetParamValue(Params, "action");
            if ((oAction != null) && (oAction.ToString() == "generalsettsave"))
                {
                    UpdateSettings(Params, ref Settings.Data.Main.SDFFilename, "sdffilename", false);
                    //Result += "<script language=\"javascript\" type=\"text/javascript\">alert('Для применения настроек необходимо перезапустить сервис');</script>";
                }
            Result += "<table width=100%>";
            Result += "<tr><td style=\"text-align:left\">Расположение файла</td>";
            Result += "<td style=\"text-align:right\"><input size=\"75\" name=\"sdffilename\" id=\"sdffilename\" value=\"" + Settings.Data.Main.SDFFilename + "\" type=\"text\"></td></tr>";
            Result += "<tr><td style=\"text-align:right\" colspan=\"2\">";
            Result += "<input type=\"button\" value=\"Сохранить\" onclick=\"javascript:savegeneralsett()\" />";
            Result += "</td></tr>";
            Result += "</table>";
            return Result;
        }

        private string ShowSyslogSettings(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            if ((SessionData.UserID == Guid.Empty) || (SessionData.AccessLevel > 2))
            {
                Result = "Отказано в доступе";
                return Result;
            }
            List<cWebServer.stParam> Params = SessionData.Params;
            object oAction = cWebServer.GetParamValue(Params, "action");
            if ((oAction != null) && (oAction.ToString() == "syslogsettsave"))
                {
                    UpdateSettings(Params, ref Settings.Data.Syslog.Port, "syslogport", false);
                    UpdateSettings(Params, ref Settings.Data.Syslog.EventsQueueProcessingPeriod, "queueprocessingperiod", false);
                    UpdateSettings(Params, ref Settings.Data.Syslog.CachesCount, "cachescount", false);
                    UpdateSettings(Params, ref Settings.Data.Syslog.CachesCount, "cachesize", false);
                    UpdateSettings(Params, ref Settings.Data.Syslog.FlushPeriod, "flushperiod", false);
                    UpdateSettings(Params, ref Settings.Data.Syslog.DNSResolvePeriod, "dnsresolve", false);
                    UpdateSettings(Params, ref Settings.Data.Syslog.DNSResolveTimeout, "dnsresolvetimeout", false);
                    Settings.Data.Syslog.Interfaces.Clear();
                    List<cWebServer.stParam> Interfaces = cWebServer.FindParams(Params, "intip");
                    if (Interfaces.Count != 0)
                    {
                        foreach (cWebServer.stParam Interface in Interfaces)
                        {
                            string uid = Interface.ParamName.Substring(5);
                            object[] oInterface = new object[2];
                            oInterface[0] = cWebServer.GetParamValue(Params, "intip" + uid);
                            oInterface[1] = cWebServer.GetParamValue(Params, "intname" + uid);
                            Settings.Data.Syslog.Interfaces.Add(oInterface);
                        }
                    }
                }
            Result += "<table width=100%>";
            Result += "<tr><td style=\"text-align:left\">Порт</td>";
            Result += "<td style=\"text-align:right\"><input type=\"text\" size=\"25\" id=\"syslogport\" name=\"syslogport\" value=\"" + Settings.Data.Syslog.Port.ToString() + "\"/></td></tr>";
            Result += "<tr><td style=\"text-align:left\">Период обработки очереди сообщений (мсек)</td>";
            Result += "<td style=\"text-align:right\"><input type=\"text\" size=\"25\" id=\"queueprocessingperiod\" name=\"queueprocessingperiod\" value=\"" + Settings.Data.Syslog.EventsQueueProcessingPeriod.ToString() + "\"/></td></tr>";
            Result += "<tr><td style=\"text-align:left\">Количество буферов</td>";
            Result += "<td style=\"text-align:right\"><input type=\"text\" size=\"25\" id=\"cachescount\" name=\"cachescount\" value=\"" + Settings.Data.Syslog.CachesCount.ToString() + "\"/></td></tr>";
            Result += "<tr><td style=\"text-align:left\">Размер буфера (записей)</td>";
            Result += "<td style=\"text-align:right\"><input type=\"text\" size=\"25\" id=\"cachesize\" name=\"cachesize\" value=\"" + Settings.Data.Syslog.CacheSize.ToString() + "\"/></td></tr>";
            Result += "<tr><td style=\"text-align:left\">Период сохранения (сек)</td>";
            Result += "<td style=\"text-align:right\"><input type=\"text\" size=\"25\" id=\"flushperiod\" name=\"flushperiod\" value=\"" + Settings.Data.Syslog.FlushPeriod.ToString() + "\"/></td></tr>";
            Result += "<tr><td style=\"text-align:left\">Период разрешения DNS-имен (сек)</td>";
            Result += "<td style=\"text-align:right\"><input type=\"text\" size=\"25\" id=\"dnsresolve\" name=\"dnsresolve\" value=\"" + Settings.Data.Syslog.DNSResolvePeriod.ToString() + "\"/></td></tr>";
            Result += "<tr><td style=\"text-align:left\">Таймаут разрешения DNS-имени (сек)</td>";
            Result += "<td style=\"text-align:right\"><input type=\"text\" size=\"25\" id=\"dnsresolvetimeout\" name=\"dnsresolvetimeout\" value=\"" + Settings.Data.Syslog.DNSResolveTimeout.ToString() + "\"/></td></tr>";
            Result += "<tr><td style=\"vertical-align:top\">Интерфейсы</td>";
            Result += "<td style=\"text-align:right\"><table id=\"inttable\" align=\"right\">";
            Result += "<tr class=\"tableheader\"><td>IP-адрес</td><td>Интерфейс</td></tr>";
            if (Settings.Data.Syslog.Interfaces.Count != 0)
            {

                foreach (object[] Interfaces in Settings.Data.Syslog.Interfaces)
                {
                    Guid IntUID = Guid.NewGuid();
                    Result += "<tr id=\"introw" + IntUID.ToString() + "\"><td><input type=\"text\" size=\"25\" id=\"intip" + IntUID.ToString() + "\" name=\"intip" + IntUID.ToString() + "\" value=\"" + Interfaces[0].ToString() + "\"/></td>";
                    Result += "<td><input type=\"text\" size=\"25\" id=\"intname" + IntUID.ToString() + "\" name=\"intname" + IntUID.ToString() + "\" value=\"" + Interfaces[1].ToString() + "\"/></td>";
                    Result += "<td><a href=\"javascript:RemoveIntRow('" + IntUID.ToString() + "')\"><img id=\"delete" + IntUID.ToString() + "\" name=\"delete" + IntUID.ToString() + "\" src=\"img/delete_g.png\" alt=\"Удалить строку\" onmouseover=\"javascript:ChangeImg('delete" + IntUID.ToString() + "', 7)\" onmouseout=\"javascript:ChangeImg('delete" + IntUID.ToString() + "', 6)\"></a></td></tr>";
                }
            }
            Result += "</table><br><a href=\"javascript:AddIntRow()\"><img id=\"addint\" name=\"addint\" src=\"img/addint_g.png\" onmouseover=\"javascript:ChangeImg('addint', 9)\" onmouseout=\"javascript:ChangeImg('addint', 8)\">";
            Result += "</td></tr>";
            Result += "<tr><td style=\"text-align:right\" colspan=\"2\">";
            Result += "<input type=\"button\" value=\"Сохранить\" onclick=\"javascript:savesyslogsett()\" />";
            Result += "</td></tr>";
            Result += "</table>";
            return Result;
        }

        private string ShowWebserverSettings(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            if ((SessionData.UserID == Guid.Empty) || (SessionData.AccessLevel > 2))
            {
                Result = "Отказано в доступе";
                return Result;
            }
            List<cWebServer.stParam> Params = SessionData.Params;
            object oAction = cWebServer.GetParamValue(Params, "action");
            if ((oAction != null) && (oAction.ToString() == "webserversettsave"))
                {
                    UpdateSettings(Params, ref Settings.Data.Webserver.Port, "webport", false);
                    UpdateSettings(Params, ref Settings.Data.Webserver.SessionTimeout, "sessiontimeout", false);
                    UpdateSettings(Params, ref Settings.Data.Webserver.TempDirClearPeriod, "tempdirclear", false);
                    UpdateSettings(Params, ref Settings.Data.Webserver.wwwPath, "wwwpath", false);
                }
            Result += "<table width=100%>";
            Result += "<tr><td style=\"text-align:left\">Порт</td>";
            Result += "<td style=\"text-align:right\"><input size=\"25\" name=\"webport\" id=\"webport\" value=\"" + Settings.Data.Webserver.Port.ToString() + "\"type=\"text\"></td></tr>";
            Result += "<tr><td style=\"text-align:left\">Таймаут сессии (сек)</td>";
            Result += "<td style=\"text-align:right\"><input size=\"25\" name=\"sessiontimeout\" id=\"sessiontimeout\" value=\"" + Settings.Data.Webserver.SessionTimeout.ToString() + "\"type=\"text\"></td></tr>";
            Result += "<tr><td style=\"text-align:left\">Период очистки временной директории (сек)</td>";
            Result += "<td style=\"text-align:right\"><input size=\"25\" name=\"tempdirclear\" id=\"tempdirclear\" value=\"" + Settings.Data.Webserver.TempDirClearPeriod.ToString() + "\"type=\"text\"></td></tr>";
            Result += "<tr><td style=\"text-align:left\">Расположение директории www</td>";
            Result += "<td style=\"text-align:right\"><input size=\"75\" name=\"wwwpath\" id=\"wwwpath\" value=\"" + Settings.Data.Webserver.wwwPath + "\"type=\"text\"></td></tr>";
            Result += "<tr><td style=\"text-align:right\" colspan=\"2\">";
            Result += "<input type=\"button\" value=\"Сохранить\" onclick=\"javascript:savewebserversett()\" />";
            Result += "</td></tr>";
            Result += "</table>";
            return Result;
        }

        private string ShowReportMaxDetailed(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            List<cWebServer.stParam> Params = SessionData.Params;
            if ((SessionData.UserID == Guid.Empty) || (SessionData.AccessLevel > 3))
            {
                Result = "%include(403.htm)include%";
                return Result;
            }
            if (cWebServer.GetParamValue(Params, "showreport") == null)
            {
                Result = "<div style=\"text-align:center\">Введите параметры и нажмите кнопку \"Сформировать\"</div>";
                return Result;
            }
            DateTime ReportStart = DateTime.Now;
            //int RowsPerPage = 100;
            object oParamValue = cWebServer.GetParamValue(Params, "page");
            //int iPageNum;
            //if (oParamValue == null)
            //    iPageNum = 1;
            //else
            //    iPageNum = Convert.ToInt32(oParamValue);
            bool PeriodEnable;
            bool UserEnable;
            bool SrcEnable;
            bool DstEnable;
            DateTime PeriodStart = DateTime.Now;
            DateTime PeriodEnd = DateTime.Now;
            Guid UserID = Guid.Empty;
            Guid SrcAddress = Guid.Empty;
            Guid DstAddress = Guid.Empty;

            #region check for period selected
            CultureInfo ci = new CultureInfo("ru-RU");

            oParamValue = cWebServer.GetParamValue(Params, "periodEnable");
            if ((oParamValue != null) && (oParamValue.ToString() != string.Empty))
                PeriodEnable = (oParamValue.ToString() == "on");
            else
                PeriodEnable = false;
            try
            {
                if (PeriodEnable)
                {
                    oParamValue = cWebServer.GetParamValue(Params, "PeriodStart");
                    if (oParamValue != null)
                        PeriodStart = DateTime.Parse(oParamValue.ToString(), ci);
                    else
                        throw new Exception();
                    oParamValue = cWebServer.GetParamValue(Params, "PeriodEnd");
                    if (oParamValue != null)
                        PeriodEnd = DateTime.Parse(oParamValue.ToString(), ci);
                    else
                        throw new Exception();
                }
            }
            catch
            {
                PeriodEnable = false;
            }
            #endregion

            #region check for user selected
            oParamValue = cWebServer.GetParamValue(Params, "userEnable");
            if ((oParamValue != null) && (oParamValue.ToString() != string.Empty))
                UserEnable = (oParamValue.ToString() == "on");
            else
                UserEnable = false;
            if (UserEnable)
            {
                oParamValue = cWebServer.GetParamValue(Params, "UserID");
                if ((oParamValue != null) && (oParamValue.ToString() != string.Empty))
                    UserID = new Guid(oParamValue.ToString());
                else
                    UserEnable = false;
            }
            #endregion

            #region check for src address selected
            oParamValue = cWebServer.GetParamValue(Params, "SrcEnable");
            if ((oParamValue != null) && (oParamValue.ToString() != string.Empty))
                SrcEnable = (oParamValue.ToString() == "on");
            else
                SrcEnable = false;
            if (SrcEnable)
            {
                oParamValue = cWebServer.GetParamValue(Params, "SrcAddress");
                if ((oParamValue != null) && (oParamValue.ToString() != string.Empty))
                {
                    object oSrcAddress = db.GetQueryObject("select addressid from taddresses where ipaddress = '" + oParamValue.ToString() + "'");
                    if (!DBNull.Value.Equals(oSrcAddress))
                        SrcAddress = new Guid(oSrcAddress.ToString());
                    else
                        SrcEnable = false;
                }
                else
                    SrcEnable = false;
            }
            #endregion

            #region check for dst address selected
            oParamValue = cWebServer.GetParamValue(Params, "DstEnable");
            if ((oParamValue != null) && (oParamValue.ToString() != string.Empty))
                DstEnable = (oParamValue.ToString() == "on");
            else
                DstEnable = false;
            if (DstEnable)
            {
                oParamValue = cWebServer.GetParamValue(Params, "DstAddress");
                if ((oParamValue != null) && (oParamValue.ToString() != string.Empty))
                {
                    object oDstAddress = db.GetQueryObject("select addressid from taddresses where ipaddress = '" + oParamValue.ToString() + "'");
                    if (!DBNull.Value.Equals(oDstAddress))
                        DstAddress = new Guid(oParamValue.ToString());
                    else
                        DstEnable = false;
                }
                else
                    DstEnable = false;
            }
            #endregion

            object oOrder = cWebServer.GetParamValue(Params, "order");
            string Order = string.Empty;
            if (oOrder != null)
                Order = oOrder.ToString();

            string DropActionID = db.GetQueryValue("select actionid from tactions where name = 'drop'");

            string WhereString = " WHERE ((NOT TL.Received = 0) OR (NOT TL.Transferred = 0))";
            if (DropActionID != string.Empty)
                WhereString += " AND (NOT TAct1.actionid = '" + DropActionID + "')";

            if (PeriodEnable)
            {
                if (WhereString.Length > 0)
                    WhereString += " AND ";
                WhereString += "(TL.DTStamp BETWEEN '" + PeriodStart.ToString("yyyy-MM-dd HH:mm:ss") + "' AND '" + PeriodEnd.ToString("yyyy-MM-dd HH:mm:ss") + "')";
            }
            if (UserEnable)
            {
                if (WhereString.Length > 0)
                    WhereString += " AND ";
                WhereString += "(TU1.UserID = '" + UserID.ToString() + "' OR TU2.UserID = '" + UserID.ToString() + "')";

            }
            if (SrcEnable)
            {
                if (WhereString.Length > 0)
                    WhereString += " AND ";
                WhereString += "(TL.SrcID = '" + SrcAddress.ToString() + "')";
            }

            if (DstEnable)
            {
                if (WhereString.Length > 0)
                    WhereString += " AND ";
                WhereString += "(TL.DstID = '" + DstAddress.ToString() + "')";
            }

            //                        string Query = @"SELECT Count(*)
            //	                                    FROM TLog TL left join
            //	                                    TAddresses TA1 on TA1.AddressID = TL.SrcID left join
            //	                                    Taddresses TA2 on TA2.AddressID = TL.DstID left join
            //	                                    TInterfaces TI1 on TI1.InterfaceID = TL.RecvIfID left join
            //	                                    TInterfaces TI2 on TI2.InterfaceID = TL.DestIfID left join
            //	                                    TActions TAct1 on TAct1.ActionID = TL.ActionID left join
            //	                                    TUsers TU1 on TU1.AddressID = TA1.AddressID left join
            //	                                    TUsers TU2 on TU2.AddressID = TA2.AddressID left join
            //	                                    TProtos TP1 on TP1.ProtoID = TL.ProtoID";

            string Query = @"SELECT TA1.hostname [Адрес источника], TA2.hostname [Адрес назначения],
                                        sum(received) [Получено], sum(transferred) [Передано] from tlog TL
                                        left join TAddresses TA1 on TL.srcid = TA1.addressid 
                                        left join Taddresses TA2 on TL.dstid = TA2.Addressid
                                        left join TActions TAct1 on TL.ActionID = TAct1.ActionID 
                                        left join TUsers TU1 on TL.srcid = TU1.addressID
                                        left join TUsers TU2 on TL.dstid = TU2.addressID";
            if (WhereString != string.Empty)
                Query += WhereString;

            Query += " GROUP BY TA1.hostname, TA2.hostname";

            string OrderString = string.Empty;

            if (Order != string.Empty)
            {
                OrderString = " ORDER BY ";
                string[] OrderDetails = Order.Split('_');
                switch (OrderDetails[0])
                {
                    case "0":
                        {
                            OrderString += "TA1.hostname ";
                            break;
                        }
                    case "1":
                        {
                            OrderString += "TA1.hostname ";
                            break;
                        }
                    case "2":
                        {
                            OrderString += "[Получено] ";
                            break;
                        }
                    case "3":
                        {
                            OrderString += "[Передано] ";
                            break;
                        }
                }
                OrderString += OrderDetails[1];
            }

            if (OrderString != string.Empty)
                Query += OrderString;



            //int TotalRows = (int)db.GetQueryObject(Query);

            DataTable DT = db.GetQueryTable(Query);
            if (DT.Rows.Count > 0)
            {

                //                            Query = @"SELECT 
                //		                        TA1.IPAddress SrcIPAddress
                //		                        ,TU1.FullName SrcUserID
                //		                        ,TA2.IPAddress DstIPAddress
                //		                        ,TU2.FullName DstUserID
                //		                        ,DTStamp		                        
                //		                        ,Received
                //		                        ,Transferred
                //		                        ,TI1.Name RecievedIf
                //		                        ,TI2.Name DestinationIf
                //		                        ,TAct1.Name Action
                //		                        ,TP1.Name IPProto
                //		                        ,IPDataLen
                //	                            FROM TLog TL left join
                //	                            TAddresses TA1 on TA1.AddressID = TL.SrcID left join
                //	                            Taddresses TA2 on TA2.AddressID = TL.DstID left join
                //	                            TInterfaces TI1 on TI1.InterfaceID = TL.RecvIfID left join
                //	                            TInterfaces TI2 on TI2.InterfaceID = TL.DestIfID left join
                //	                            TActions TAct1 on TAct1.ActionID = TL.ActionID left join
                //	                            TUsers TU1 on TU1.AddressID = TA1.AddressID left join
                //	                            TUsers TU2 on TU2.AddressID = TA2.AddressID left join
                //	                            TProtos TP1 on TP1.ProtoID = TL.ProtoID";
                //                            if (WhereString != string.Empty)
                //                                Query += " WHERE " + WhereString;
                //                            Query += " order by TA1.IPAddress offset " + ((iPageNum - 1) * RowsPerPage).ToString() +
                //                                    " rows fetch next " + RowsPerPage.ToString() + " rows only";

                //DataTable DT = db.GetQueryTable(Query);                            
                Result = "<table width=\"100%\">";
                Result += "<tr>";
                int i = 0;
                foreach (DataColumn DC in DT.Columns)
                {
                    List<cWebServer.stParam> P1 = Params;
                    string NewSortValue = "asc";
                    if (Order != string.Empty)
                    {
                        if (Order.Split('_')[0] == i.ToString())
                        {
                            if (Order.Split('_')[1] == "asc")
                                NewSortValue = "desc";
                        }
                    }
                    cWebServer.UpdateParams(P1, "Order", i.ToString() + "_" + NewSortValue);
                    Result += "<td style=\"border: 1px solid #000000;\"><strong>";
                    Result += "<a href=\"reportdata1.wcmd?" + cWebServer.ParamsToURI(P1) + "\">";
                    Result += DC.ColumnName;
                    Result += "</a>";
                    Result += "</strong>";
                    if (Order != string.Empty)
                    {
                        if (Order.Split('_')[0] == i.ToString())
                        {
                            Result += "<img src = \"img/sort_" + Order.Split('_')[1] + ".png\" />";
                        }
                    }
                    Result += "</td>";
                    i++;
                }
                Result += "</tr>";
                i = 1;
                foreach (DataRow DR in DT.Rows)
                {
                    Result += "<tr";
                    if (i % 2 == 0)
                        Result += " style=\"background-color: #AACCFF\"";
                    Result += ">";
                    foreach (object Cell in DR.ItemArray)
                    {
                        Result += "<td style=\"border: 1px solid #000000;\">";
                        if (!DBNull.Value.Equals(Cell))
                        {
                            try
                            {
                                Result += BytesToMultipleBytes((Int64)Cell, false, 2);
                            }
                            catch
                            {
                                Result += Cell.ToString();

                            }
                        }
                        else
                            Result += "&nbsp;";
                        Result += "</td>";
                    }
                    Result += "</tr>";
                    i++;
                }
                Result += "</table><Br/>";

                //for (i = 0; i < TotalRows; i += RowsPerPage)
                //{
                //    if (iPageNum == (i / 100 + 1))
                //        Result += "[" + (i / 100 + 1).ToString() + "] ";
                //    else
                //    {
                //        Result += "<a href=\"reportdata.htm?page=" + (i / 100 + 1).ToString();
                //        if (PeriodEnable)
                //            Result += "&periodenable=on&periodstart=" + PeriodStart.ToString("dd.mm.yyyy") + "&periodend=" + PeriodEnd.ToString("dd.mm.yyyy");
                //        if (UserEnable)
                //            Result += "&userenable=on&userid=" + UserID.ToString();
                //        if (SrcEnable)
                //            Result += "&srcenable=on&srcaddress=" + SrcAddress.ToString();
                //        if (DstEnable)
                //            Result += "&dstenable=on&dstaddress=" + DstAddress.ToString();
                //        Result += "\">" + (i / 100 + 1).ToString() + "</a> ";
                //    }

                //}

                TimeSpan ReportTime = DateTime.Now - ReportStart;
                Result += "<div style=\"text-align:right\">Report creating time: " + ReportTime.ToString() + "</div>";

            }
            else
            {
                Result += "<div style=\"text-align:center\">Нет данных, удовлетворяющих данным условиям</div>";
            }
            return Result;
        }

        private string ShowGraphicByUsers(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            if ((SessionData.UserID == Guid.Empty) || (SessionData.AccessLevel > 3))
            {
                Result = "Отказано в доступе";
                return Result;
            }
            DateTime ReportStart = DateTime.Now;
            List<cWebServer.stParam> Params = SessionData.Params;
            CultureInfo ci = new CultureInfo("ru-RU");
            DateTime PeriodStart;
            DateTime PeriodEnd;
            try
            {
                object oParamValue = cWebServer.GetParamValue(Params, "PeriodStartByUser");
                if (oParamValue != null)
                    PeriodStart = DateTime.Parse(oParamValue.ToString(), ci);
                else
                    throw new Exception();
            }
            catch
            {
                PeriodStart = DateTime.Now.Date;
            }

            try
            {
                object oParamValue = cWebServer.GetParamValue(Params, "PeriodEndByUser");
                if (oParamValue != null)
                    PeriodEnd = DateTime.Parse(oParamValue.ToString(), ci);
                else
                    throw new Exception();
            }
            catch
            {
                PeriodEnd = DateTime.Now.AddDays(1).Date;
            }

            string DropActionID = db.GetQueryValue("select actionid from tactions where name = 'drop'");
            string Wan1ID = db.GetQueryValue("select InterfaceID from TInterfaces where Name ='wan1'"); // wan1 надо будет заменить на внешний интерфейс из настроек
            string Query = @"select TU1.FullName [Имя пользователя], sum(received) [Получено], 
                        'report2userdetailed.wcmd?addressid='+Cast(TL.SrcId as nvarchar(36))+'&periodstart=" + PeriodStart.ToString("dd.MM.yyyy") + "&periodend=" + PeriodEnd.ToString("dd.MM.yyyy") + @"' from tLog TL
                                            left join Tusers TU1 on TU1.AddressID = TL.SrcID";
            if (DropActionID != string.Empty)
                Query += @" where (not TL.ActionID = '" + DropActionID + "') AND " +
                    "(TL.DestIfID = '" + Wan1ID + "') AND " +
                    "(TL.DTStamp BETWEEN '" + PeriodStart.ToString("yyyy-MM-dd HH:mm:ss") +
                    "' AND '" + PeriodEnd.ToString("yyyy-MM-dd HH:mm:ss") + "')";
            Query += @" group by TU1.FullName, TL.SrcId
                                            having (NOT TU1.FullName is null)
                                    Order by [Получено] desc";

            object oChartType = cWebServer.GetParamValue(Params, "charttype");
            int iChartType = 1;
            try
            {
                iChartType = Convert.ToInt32(oChartType);
            }
            catch
            { }

            cGraphic Graphic = new cGraphic();

            Graphic.MapName = "ReportMap";
            Graphic.LinkTarget = "ReportUserDetailed";
            Graphic.BytesToMultipleBytes += BytesToMultipleBytes;
            Graphic.ErrorHandler += delegate(Exception ex)
            {
                if (ErrorHandler != null)
                {
                    ErrorHandler(new Exception("Ошибка при построении графика: "+ex.Message, ex));
                    throw ex;
                }
            };
            Graphic.GetQueryTable += delegate(string sQuery)
            {
                return db.GetQueryTable(sQuery);
            };
            Graphic.Query = Query;
            int GraphicResult = 1;
            switch (iChartType)
            {
                case 1:
                default:
                    {
                        GraphicResult = Graphic.CreateChartBar(550, 400, cGraphic.eChartOrientation.Vertical);
                        break;
                    }
                case 2:
                    {
                        GraphicResult = Graphic.CreateChartBar(550, 400, cGraphic.eChartOrientation.Horizontal);
                        break;
                    }
                case 3:
                    {
                        GraphicResult = Graphic.CreateChartCircle(550, 400);
                        break;
                    }
            }

            if (GraphicResult == 0)
            {
                string ImgName = Graphic.SaveFile(Path.Combine(WebServer.GetWWWPath(), "tmp"), System.Drawing.Imaging.ImageFormat.Png);
                Result += "<img src=\"tmp/" + Path.GetFileName(ImgName) + "\" usemap=\"#ReportMap\"/>";
                Result += Graphic.Map;
            }
            else
            {
                if (GraphicResult == 2)
                    Result += "Нет данных";
                else
                    Result += "Ошибка при создании изображения";
            }



            return Result;
        }

        private string ShowReportByUsers(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            if ((SessionData.UserID == Guid.Empty) || (SessionData.AccessLevel > 3))
            {
                Result = "Отказано в доступе";
                return Result;
            }
            DateTime ReportStart = DateTime.Now;
            List<cWebServer.stParam> Params = SessionData.Params;
            CultureInfo ci = new CultureInfo("ru-RU");
            DateTime PeriodStart;
            DateTime PeriodEnd;
            try
            {
                object oParamValue = cWebServer.GetParamValue(Params, "PeriodStartByUser");
                if (oParamValue != null)
                    PeriodStart = DateTime.Parse(oParamValue.ToString(), ci);
                else
                    throw new Exception();
            }
            catch
            {
                PeriodStart = DateTime.Now.Date;
            }

            try
            {
                object oParamValue = cWebServer.GetParamValue(Params, "PeriodEndByUser");
                if (oParamValue != null)
                    PeriodEnd = DateTime.Parse(oParamValue.ToString(), ci);
                else
                    throw new Exception();
            }
            catch
            {
                PeriodEnd = DateTime.Now.AddDays(1).Date;
            }

            string DropActionID = db.GetQueryValue("select actionid from tactions where name = 'drop'");
            string Wan1ID = db.GetQueryValue("select InterfaceID from TInterfaces where Name ='wan1'"); // wan1 надо будет заменить на внешний интерфейс из настроек
            Int64 iDroppedReceived = 0;
            Int64 iDroppedTransferred = 0;
            if ((DropActionID != string.Empty) && (Wan1ID != string.Empty))
            {
                object oDroppedReceived = db.GetQueryObject(@"select sum(ipdatalen)  from Tlog TL
                                    where (TL.ActionID = '" + DropActionID + @"') and (TL.RecvIfID = '" + Wan1ID + @"')
                                    AND (TL.DTStamp BETWEEN '" + PeriodStart.ToString("yyyy-MM-dd HH:mm:ss") +
                        @"' AND '" + PeriodEnd.ToString("yyyy-MM-dd HH:mm:ss") + "')");
                object oDroppedTransferred = db.GetQueryObject(@"select sum(ipdatalen)  from Tlog TL
                                    where (TL.ActionID = '" + DropActionID + @"') and (not TL.RecvIfID = '" + Wan1ID + @"')
                                    AND (TL.DTStamp BETWEEN '" + PeriodStart.ToString("yyyy-MM-dd HH:mm:ss") +
                        @"' AND '" + PeriodEnd.ToString("yyyy-MM-dd HH:mm:ss") + "')");

                    iDroppedReceived = Convert.ToInt64(DB.ISNULL(oDroppedReceived, true));
                    iDroppedTransferred = Convert.ToInt64(DB.ISNULL(oDroppedTransferred, true));
            }

            object oOrder = cWebServer.GetParamValue(Params, "order");
            string Order = string.Empty;
            if (oOrder != null)
                Order = oOrder.ToString();

            if (Order == string.Empty)
                Order = "0_asc";


            string Query = @"select TA1.IPAddress [IP адрес], TU1.FullName [Имя пользователя], sum(received) [Получено], sum(transferred) [Передано], TL.SrcId from tLog TL
                                            left join TAddresses TA1 on TA1.AddressID = TL.SrcID
                                            left join Tusers TU1 on TU1.AddressID = TL.SrcID";
            if (DropActionID != string.Empty)
                Query += @" where (not TL.ActionID = '" + DropActionID + "') AND " +
                    "(TL.DestIfID = '" + Wan1ID + "') AND " +
                    "(TL.DTStamp BETWEEN '" + PeriodStart.ToString("yyyy-MM-dd HH:mm:ss") +
                    "' AND '" + PeriodEnd.ToString("yyyy-MM-dd HH:mm:ss") + "')";
            Query += @" group by TA1.IPAddress, TU1.FullName, TL.SrcId
                                            having (NOT TU1.FullName is null)";

            string OrderString = " ORDER BY ";
            string[] OrderDetails = Order.Split('_');
            switch (OrderDetails[0])
            {
                case "0":
                    {
                        OrderString += "TA1.IPAddress ";
                        break;
                    }
                case "1":
                    {
                        OrderString += "TU1.FullName ";
                        break;
                    }
                case "2":
                    {
                        OrderString += "[Получено] ";
                        break;
                    }
                case "3":
                    {
                        OrderString += "[Передано] ";
                        break;
                    }
            }
            OrderString += OrderDetails[1];
            Query += OrderString;

            bool[] ShowingColumns = new bool[] { true, true, true, true, false };
            int ShowingColumnsCount = GetShowingColumnsCount(ShowingColumns);

            DataTable DT = db.GetQueryTable(Query);

            Result += "<table width=100%>";

            if ((iDroppedReceived == 0) && (iDroppedTransferred == 0) && (DT.Rows.Count == 0))
            {
                Result += "<tr>";
                Result += "<td colspan = " + DT.Columns.Count + ">";
                Result += "Нет данных";
                Result += "</tr>";
            }
            else
            {
                Result += "<tr class=\"tableheader\">";
                int i = 0;
                List<cWebServer.stParam> P1 = Params;
                foreach (DataColumn DC in DT.Columns)
                {
                    if (!ShowingColumns[i])
                        continue;
                    string NewSortValue = "asc";
                    if (Order.Split('_')[0] == i.ToString())
                    {
                        if (Order.Split('_')[1] == "asc")
                            NewSortValue = "desc";
                    }
                    cWebServer.UpdateParams(P1, "Order", i.ToString() + "_" + NewSortValue);
                    Result += "<td>";
                    Result += "<a href=\"report2byuser.htm?" + cWebServer.ParamsToURI(P1) + "\">";
                    Result += DC.ColumnName;
                    if (Order.Split('_')[0] == i.ToString())
                    {
                        Result += "&nbsp;<img src = \"img/sort_" + Order.Split('_')[1] + ".png\" />";
                    }
                    Result += "</td>";
                    i++;
                }
                Result += "</tr>";

                if (DT.Rows.Count > 0)
                {
                    int j = 0;
                    foreach (DataRow DR in DT.Rows)
                    {
                        if ((j % 2) == 0)
                            Result += "<tr>";
                        else
                            Result += "<tr class=\"odd\">";
                        int k = 0;
                        foreach (object Cell in DR.ItemArray)
                        {
                            if (!ShowingColumns[k])
                                continue;
                            Result += "<td>";
                            if (k == 0)
                                Result += "<a href=\"report2userdetailed.wcmd?addressid=" + DR[4].ToString() + "&periodstart=" + PeriodStart.ToString("dd.MM.yyyy") + "&periodend=" + PeriodEnd.ToString("dd.MM.yyyy") + "\" target=\"ReportUserDetailed\">";
                            try
                            {
                                Result += BytesToMultipleBytes((Int64)Cell, false, 2);
                            }
                            catch
                            {
                                Result += Cell.ToString();
                            }
                            if (k == 0)
                                Result += "</a>";
                            Result += "</td>";

                            k++;
                        }
                        Result += "</tr>";
                        j++;
                    }
                }
                if ((iDroppedReceived != 0) || (iDroppedTransferred != 0))
                {
                    Result += "<tr>";
                    Result += "<td colspan=" + (ShowingColumnsCount - 2).ToString() + ">";
                    Result += "Отброшенные пакеты";
                    Result += "</td><td>" + BytesToMultipleBytes(iDroppedReceived, false, 2) + "</td><td>" + BytesToMultipleBytes(iDroppedTransferred, false, 2) + "</td>";
                    Result += "</tr>";
                }
                Query = @"select 
                                            sum(received), sum(transferred) from tLog TL                                            
                                            left join Tusers TU1 on TU1.AddressID = TL.SrcID";
                string WhereString = " WHERE";
                if (DropActionID != string.Empty)
                    WhereString += @" (not TL.ActionID = '" + DropActionID + "') AND ";
                WhereString += @" (not tu1.userid is null) AND" +
                    @" (TL.DTStamp BETWEEN '" + PeriodStart.ToString("yyyy-MM-dd HH:mm:ss") +
                    @"' AND '" + PeriodEnd.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                Query += WhereString;
                DataTable DTSum = db.GetQueryTable(Query);
                Result += "<tr>";
                Result += "<td colspan=" + (ShowingColumnsCount - 2).ToString() + ">";
                Result += "Суммарно";
                Result += "</td>";
                Result += "<td>" + BytesToMultipleBytes(Convert.ToInt64(DB.ISNULL(DTSum.Rows[0][0], true)) + iDroppedReceived, false, 2);
                Result += "</td>";
                Result += "<td>" + BytesToMultipleBytes(Convert.ToInt64(DB.ISNULL(DTSum.Rows[0][1], true)) + iDroppedTransferred, false, 2);
                Result += "</td>";
                Result += "</tr>";
            }
            Result += "</table>";


            TimeSpan ReportTime = DateTime.Now - ReportStart;
            Result += "<div style=\"text-align:right\">Report creating time: " + ReportTime.ToString() + "</div>";
            return Result;
        }

        private string ShowPeriodByUsers(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            DateTime PeriodStart;
            DateTime PeriodEnd;
            CultureInfo ci = new CultureInfo("ru-RU");
            try
            {
                object oParamValue = cWebServer.GetParamValue(SessionData.Params, "PeriodStartByUser");
                if (oParamValue != null)
                    PeriodStart = DateTime.Parse(oParamValue.ToString(), ci);
                else
                    throw new Exception();
            }
            catch
            {
                PeriodStart = DateTime.Now.Date;
            }

            try
            {
                object oParamValue = cWebServer.GetParamValue(SessionData.Params, "PeriodEndByUser");
                if (oParamValue != null)
                    PeriodEnd = DateTime.Parse(oParamValue.ToString(), ci);
                else
                    throw new Exception();
            }
            catch
            {
                PeriodEnd = DateTime.Now.AddDays(1).Date;
            }
            Result = "с " + PeriodStart.ToString("dd.MM.yyyy") + " по " + PeriodEnd.ToString("dd.MM.yyyy");
            return Result;
        }

        private string ShowReportUserDetailed(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            if ((SessionData.UserID == Guid.Empty) || (SessionData.AccessLevel > 3))
            {
                Result = "%include(403.htm)include%";
                return Result;
            }
            DateTime ReportStart = DateTime.Now;

            List<cWebServer.stParam> Params = SessionData.Params;
            CultureInfo ci = new CultureInfo("ru-RU");


            object oAddressID = cWebServer.GetParamValue(Params, "addressid");
            if (oAddressID == null)
                return Result;
            string sAddressID = oAddressID.ToString();
            try
            {
                new Guid(sAddressID);
            }
            catch
            {
                return Result;
            }

            DateTime PeriodStart;
            DateTime PeriodEnd;
            try
            {
                object oParamValue = cWebServer.GetParamValue(Params, "PeriodStart");
                if (oParamValue != null)
                    PeriodStart = DateTime.Parse(oParamValue.ToString(), ci);
                else
                    throw new Exception();
            }
            catch
            {
                PeriodStart = DateTime.Now.Date;
            }

            try
            {
                object oParamValue = cWebServer.GetParamValue(Params, "PeriodEnd");
                if (oParamValue != null)
                    PeriodEnd = DateTime.Parse(oParamValue.ToString(), ci);
                else
                    throw new Exception();
            }
            catch
            {
                PeriodEnd = DateTime.Now.AddDays(1).Date;
            }

            string DropActionID = db.GetQueryValue("select actionid from tactions where name = 'drop'");
            string Wan1ID = db.GetQueryValue("select InterfaceID from TInterfaces where Name ='wan1'"); // wan1 надо будет заменить на внешний интерфейс из настроек


            object oOrder = cWebServer.GetParamValue(Params, "order");
            string Order = string.Empty;
            if (oOrder != null)
                Order = oOrder.ToString();

            if (Order == string.Empty)
                Order = "2_desc";

            string Query = @"Select TA1.IPAddress [IP адрес], TA1.hostname [Имя узла], sum(received) [Получено], sum(transferred) [Передано] from TLog TL
                                            inner join TAddresses TA1 on TL.DstID = TA1.AddressID
                                            where (tl.srcid = '" + sAddressID + "')";
            if (DropActionID != string.Empty)
                Query += "and (not TL.ActionID = '" + DropActionID + "') AND (TL.DestIfID='" + Wan1ID + "')";
            Query += @" AND (TL.DTStamp BETWEEN '" + PeriodStart.ToString("yyyy-MM-dd HH:mm:ss") +
                    @"' AND '" + PeriodEnd.ToString("yyyy-MM-dd HH:mm:ss") + "')";
            Query += "group by TA1.IPAddress, TA1.hostname";

            string OrderString = " ORDER BY ";
            string[] OrderDetails = Order.Split('_');
            switch (OrderDetails[0])
            {
                case "0":
                    {
                        OrderString += "TA1.IPAddress ";
                        break;
                    }
                case "1":
                    {
                        OrderString += "TA1.hostname ";
                        break;
                    }
                case "2":
                    {
                        OrderString += "[Получено] ";
                        break;
                    }
                case "3":
                    {
                        OrderString += "[Передано] ";
                        break;
                    }
            }
            OrderString += OrderDetails[1];
            Query += OrderString;

            DataTable DT = db.GetQueryTable(Query);
            DataTable UserInfo = db.GetQueryTable(@"Select TA.IPAddress, TU.FullName from TUsers TU
                                                    left join TAddresses TA on TU.AddressID = TA.AddressID
                                                     where TU.addressid = '" + sAddressID + "'");
            if (UserInfo.Rows.Count > 0)
                Result += "<div style=\"text-align:center\">Отчет по пользователю " + UserInfo.Rows[0][1].ToString() + " (" + UserInfo.Rows[0][0] +
                          ") за период с " + PeriodStart.ToString("dd.MM.yyyy") + " по " + PeriodEnd.ToString("dd.MM.yyyy") + "</div>";

            Result += "<table width=100%>";
            if (DT.Rows.Count > 0)
            {
                Result += "<tr>";
                int i = 0;
                List<cWebServer.stParam> P1 = Params;
                foreach (DataColumn DC in DT.Columns)
                {
                    string NewSortValue = "asc";
                    if (Order.Split('_')[0] == i.ToString())
                    {
                        if (Order.Split('_')[1] == "asc")
                            NewSortValue = "desc";
                    }
                    cWebServer.UpdateParams(P1, "Order", i.ToString() + "_" + NewSortValue);
                    Result += "<td style=\"border: 1px solid #000000; text-align:center;\"><strong>";
                    Result += "<a href=\"report2userdetailed.wcmd?" + cWebServer.ParamsToURI(P1) + "\">";
                    Result += DC.ColumnName;
                    if (Order.Split('_')[0] == i.ToString())
                    {
                        Result += "&nbsp;<img src = \"img/sort_" + Order.Split('_')[1] + ".png\" />";
                    }
                    Result += "</strong></td>";
                    i++;
                }
                Result += "</tr>";
                foreach (DataRow DR in DT.Rows)
                {
                    Result += "<tr>";
                    foreach (object Cell in DR.ItemArray)
                    {
                        Result += "<td>";
                        try
                        {
                            Result += BytesToMultipleBytes((int)Cell, false, 2);
                        }
                        catch
                        {
                            Result += Cell.ToString();
                        }
                        Result += "</td>";

                    }
                    Result += "</tr>";
                }
            }
            else
            {
                Result += "<tr>";
                Result += "<td>";
                Result += "Нет данных";
                Result += "</tr>";
            }
            Result += "</table>";
            TimeSpan ReportTime = DateTime.Now - ReportStart;
            Result += "<div style=\"text-align:right\">Report creating time: " + ReportTime.ToString() + "</div>";
            return Result;
        }

        private string InsertUsersToCombobox(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            DataTable DT = db.GetQueryTable("Select UserID, FullName from tusers order by fullname");
            Result = DataTableToSelectControl(DT, 0, 0, 1);
            return Result;
        }

        private string InsertAccessLevelToCombobox(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            DataTable DT = db.GetQueryTable("Select AccessLevelID, Name from taccesslevels order by Name");
            Result = DataTableToSelectControl(DT, 0, 0, 1);
            return Result;
        }

        private string IsUserLoggedIn(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            if (SessionData.UserID == Guid.Empty)
                Result = "block";
            else
                Result = "none";
            return Result;
        }

        private string InsertSrcAddressToCombobox(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            DataTable DT = db.GetQueryTable("Select distinct AddressID, IPAddress from Tlog left join Taddresses on SrcID = AddressID where ipaddress is not null order by IPAddress");
            Result = DataTableToSelectControl(DT, 0, 0, 1);
            return Result;
        }

        private string InsertDstAddressToCombobox(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            DataTable DT = db.GetQueryTable("Select distinct AddressID, IPAddress from Tlog left join Taddresses on DstID = AddressID where ipaddress is not null order by IPAddress");
            Result = DataTableToSelectControl(DT, 0, 0, 1);
            return Result;
        }

        private string ShowUserList(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            if ((SessionData.UserID == Guid.Empty) || (SessionData.AccessLevel > 2))
            {
                Result = "<tr><td colspan=\"6\">Отказано в доступе</td></tr>";
                return Result;
            }
            DataTable DTAL = db.GetQueryTable("select AccessLevelID, Name from TAccessLevels order by Name");
            DataTable DTA = db.GetQueryTable("select distinct addressid, ipAddress from TAddresses order by ipaddress");

            DataTable DT = db.GetQueryTable(@"Select TU.UserID, TU.Name, TU.FullName, TAL.Name, TA.IPAddress from TUsers TU left join
                                                        TAccessLevels TAL on TU.AccessLevelID=TAL.AccessLevelID left join
                                                        TAddresses TA on TU.AddressID=TA.AddressID order by TU.Name");
            if (DT.Rows.Count != 0)
            {
                foreach (DataRow DR in DT.Rows)
                {
                    Result += "<tr id=\"Row_" + DR[0].ToString() + "\"  style=\"text-align:center\">";
                    Result += "<td>";
                    Result += "<input type=\"hidden\" name=\"UserChanged_" + DR[0].ToString() + "\" id=\"UserChanged_" + DR[0].ToString() + "\" value=\"0\">";
                    Result += "<input type=\"checkbox\" name=\"UserToDelete_" + DR[0].ToString() + "\" id=\"UserToDelete_" + DR[0].ToString() + "\">";
                    //Result += "<input type=\"hidden\" name=\"NewPass_" + DR[0].ToString() + "\" id=\"NewPass_" + DR[0].ToString() + "\" value=\"\">";
                    Result += "<input type=\"hidden\" name=\"OrigUserAccessLevel_" + DR[0].ToString() + "\" id=\"OrigUserAccessLevel_" + DR[0].ToString() + "\" value=\"" + DR[3].ToString() + "\">";
                    Result += "</td>";
                    Result += "<td>";
                    Result += "<input type=\"text\" name=\"UserName_" + DR[0].ToString() + "\" id=\"UserName_" + DR[0].ToString() + "\" value=\"" + DB.ISNULL(DR[1], false).ToString() + "\" onchange=\"javascript:UserChanged('" + DR[0].ToString() + "')\">";
                    Result += "</td>";
                    Result += "<td>";
                    Result += "<input type=\"text\" name=\"UserFullName_" + DR[0].ToString() + "\" id=\"UserFullName_" + DR[0].ToString() + "\" value=\"" + DB.ISNULL(DR[2], false).ToString() + "\" onchange=\"javascript:UserChanged('" + DR[0].ToString() + "')\">";
                    Result += "</td>";
                    Result += "<td>";
                    Result += "<select name=\"UserAccessLevel_" + DR[0].ToString() + "\" id=\"UserAccessLevel_" + DR[0].ToString() + "\" onchange=\"javascript:UserChanged('" + DR[0].ToString() + "')\">";
                    Result += DataTableToSelectControl(DTAL, DB.ISNULL(DR[3], false).ToString(), false, 0, 1);
                    Result += "</select>";
                    Result += "</td>";
                    Result += "<td>";
                    //Result += "<select name=\"UserIPAddress_" + DR[0].ToString() + "\" id=\"UserIPAddress_" + DR[0].ToString() + "\">";
                    //Result += DataTableToSelectControl(DTA, ObjectToString(DR[4]), false, 0, 1);
                    //Result += "</select>";
                    Result += "<input type=\"text\" name=\"UserIPAddress_" + DR[0].ToString() + "\" id=\"UserIPAddress_" + DR[0].ToString() + "\" value=\"" + DB.ISNULL(DR[4], false).ToString() + "\" onchange=\"javascript:UserChanged('" + DR[0].ToString() + "')\">";
                    Result += "</td>";
                    Result += "<td>";
                    Result += "<div id=\"NewPassDiv_" + DR[0].ToString() + "\">";
                    Result += "<a href=\"javascript:ChangePassword('" + DR[0].ToString() + "')\">Сменить</a>";
                    Result += "</div>";
                    Result += "</td>";
                    Result += "</tr>";
                }
            }

            return Result;
        }

        private string ShowUsersData(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            if ((SessionData.UserID == Guid.Empty) || (SessionData.AccessLevel > 2))
            {
                Result = "Отказано в доступе";
                return Result;
            }
            List<cWebServer.stParam> Params = SessionData.Params;
            object oAction = cWebServer.GetParamValue(Params, "action");
            string sAction = string.Empty;
            if ((oAction != null) && (oAction.ToString() == "userssave"))
            {

                // check for deleted users
                object oDeleteUsersCount = cWebServer.GetParamValue(Params, "deleteusercount");
                if (oDeleteUsersCount != null)
                {
                    int DeleteUserCount = Convert.ToInt32(oDeleteUsersCount);
                    List<string> UsersToDelete = new List<string>();
                    for (int i = 0; i < DeleteUserCount; i++)
                    {
                        string ID = cWebServer.GetParamValue(Params, "deleteuser_" + i.ToString()).ToString();
                        //if (ID.Length == 36)
                        UsersToDelete.Add("delete from TUsers where UserID = '" + ID + "'");
                    }
                    db.ExecuteQueryBatch(UsersToDelete);
                }
                int UsersCount = Convert.ToInt32(cWebServer.GetParamValue(Params, "UsersCount"));
                if (UsersCount > 0)
                    for (int i = 0; i < UsersCount; i++)
                    {
                        string UserID = cWebServer.GetParamValue(Params, "UserID_" + i.ToString()).ToString();
                        Guid gIPAddress = Guid.Empty;
                        string sIPAddress = cWebServer.GetParamValue(Params, "UserIPAddress_" + i.ToString()).ToString();
                        if (sIPAddress != string.Empty)
                        {
                            object oIPAddress;
                            oIPAddress = db.GetQueryObject("Select AddressID from TAddresses where IPAddress = '" + sIPAddress + "'");
                            if (DBNull.Value.Equals(oIPAddress))
                            {
                                gIPAddress = Guid.NewGuid();
                                db.ExecuteQuery("insert into taddresses (addressID, ipaddress) values ('" + gIPAddress.ToString() + "', '" + sIPAddress + "')");
                            }
                            else
                                gIPAddress = (Guid)oIPAddress;
                        }
                        string UserName = cWebServer.GetParamValue(Params, "UserName_" + i.ToString()).ToString();
                        string UserFullName = cWebServer.GetParamValue(Params, "UserFullName_" + i.ToString()).ToString();
                        string UserLevel = cWebServer.GetParamValue(Params, "UserAccessLevel_" + i.ToString()).ToString();
                        object oNewPass = cWebServer.GetParamValue(Params, "NewPass_" + i.ToString());
                        string UserPassHash = string.Empty;
                        if (oNewPass != null)
                            UserPassHash = cWebServer.GetMd5Hash(oNewPass.ToString());
                        if (UserID.Length == 36)
                        {
                            string Query = "Update TUsers set Name = '" + UserName + "', FullName = '" + UserFullName + "', AccessLevelID = '" + UserLevel + "'";
                            if (gIPAddress != Guid.Empty)
                                Query += ", AddressID = '" + gIPAddress.ToString() + "'";
                            if (UserPassHash != string.Empty)
                                Query += ", Password = '" + UserPassHash + "'";
                            Query += " where UserID = '" + UserID + "'";
                            db.ExecuteQuery(Query);
                        }
                        else
                        {
                            string Query = "Insert into TUsers (UserID, Name, FullName, Password, AccessLevelID";
                            if (gIPAddress != Guid.Empty)
                                Query += ", AddressID";
                            Query += ") values (NEWID(), '" + UserName + "', '" + UserFullName + "', '" + UserPassHash + "', '" + UserLevel + "'";
                            if (gIPAddress != Guid.Empty)
                                Query += ", '" + gIPAddress.ToString() + "'";
                            Query += ")";
                            db.ExecuteQuery(Query);
                        }
                    }
            }
            Result = "<div id=\"divUserTable\">";
            Result += "<table width=\"100%\">";
            Result += "<tr style=\"text-align: center\">";
            Result += "<td width=\"33%\">";
            Result += "<a href=\"javascript:AddRow()\">";
            Result += "<img id=\"adduser\" src=\"img/adduser_g.png\" border=\"0px\" alt=\"Добавить пользователя\"";
            Result += " onmouseover=\"javascript:ChangeImg('adduser', 1)\" onmouseout=\"javascript:ChangeImg('adduser', 0)\" />";
            Result += "</a>";
            Result += "</td>";
            Result += "<td width=\"33%\">";
            Result += "<a href=\"javascript:RemoveRows()\">";
            Result += "<img id=\"deleteuser\" src=\"img/deleteuser_g.png\" border=\"0px\" alt=\"Удалить пользователя\"";
            Result += " onmouseover=\"javascript:ChangeImg('deleteuser', 3)\" onmouseout=\"javascript:ChangeImg('deleteuser', 2)\" />";
            Result += "</a>";
            Result += "</td>";
            Result += "<td width=\"33%\">";
            Result += "<a href=\"javascript:SaveUsersData()\">";
            Result += "<img id=\"saveusers\" src=\"img/saveusers_g.png\" alt=\"Сохранить изменения\" border=\"0px\"";
            Result += " onmouseover=\"javascript:ChangeImg('saveusers', 5)\" onmouseout=\"javascript:ChangeImg('saveusers', 4)\" />";
            Result += "</a>";
            Result += "</td>";
            Result += "</tr>";
            Result += "</table>";
            Result += "<table width=\"100%\" id=\"UserTable\">";
            Result += "<tr class=\"tableheader\">";
            Result += "<td style=\"text-align: center\">";
            Result += "<input id=\"SelectAll\" type=\"checkbox\" onchange=\"javascript:SelectAllRows()\" />";
            Result += "</td>";
            Result += "<td style=\"text-align: center\">";
            Result += "Логин";
            Result += "</td>";
            Result += "<td style=\"text-align: center\">";
            Result += "Полное имя";
            Result += "</td>";
            Result += "<td style=\"text-align: center\">";
            Result += "Уровень доступа";
            Result += "</td>";
            Result += "<td style=\"text-align: center\">";
            Result += "IP-адрес";
            Result += "</td>";
            Result += "<td style=\"text-align: center\">";
            Result += "Пароль";
            Result += "</td>";
            Result += "</tr>";
            Result += "%command(ShowUserList)command%";
            Result += "</table>";
            Result += "</div>";
            return Result;
        }

        private string InsertDateNow(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            Result = DateTime.Now.ToString("dd.MM.yyyy");
            return Result;
        }

        private string InsertDateTomorrow(cWebServer.cSession SessionData)
        {
            string Result = string.Empty;
            Result = DateTime.Now.AddDays(1).ToString("dd.MM.yyyy");
            return Result;
        }
    }
}
